package tt.dz.egobus.servicemanager.core.config;

import org.apache.commons.lang3.StringUtils;
import tt.dz.egobus.servicemanager.core.resovler.ClassPrototypeEnum;

/**
 * @author Anson
 * @date 17-8-8
 * @name 基于String转换的配置
 * @since 1.0.6
 */
public abstract class StringConvertConfigAccess extends AbstractConfigAccess {

    /**
     * @param fullKey              完整的key
     * @param runtimeConfigKeyEnum 当前对应的默认值
     * @author Anson
     * @date 17-8-8
     * @name 尝试获取动态配置的最新值
     * @since 1.0.6
     */
    protected abstract String tryGetValue(String fullKey, RuntimeConfigKeyEnum runtimeConfigKeyEnum);


    @Override
    public <T> T value(String key, T defaultValue) {
        RuntimeConfigKeyEnum runtimeConfigKeyEnum = RuntimeConfigKeyEnum.indexOf(key);
        String fullKey = this.keyRuntimeConfigKeyEmunConvert(runtimeConfigKeyEnum);
        if (defaultValue == null) {
            defaultValue = (T) runtimeConfigKeyEnum.getDefaultValue();
        }
        if (StringUtils.isBlank(fullKey)) {
            return defaultValue;
        }
        String remoteValue = this.tryGetValue(fullKey, runtimeConfigKeyEnum);
        if (StringUtils.isBlank(remoteValue)) {
            return defaultValue;
        }
        Class<T> clazz = (Class<T>) defaultValue.getClass();
        T t = ClassPrototypeEnum.valueOfKey(runtimeConfigKeyEnum.getShortClassName()).value(remoteValue, clazz);
        return t == null ? defaultValue : t;
    }
}
